module("AnimMenu", package.seeall)

local AnimMenu = class("AnimMenu")

AnimMenu = class("AnimMenu",
    function(node)
        return node
    end
)

function create(node, level)
	local self = AnimMenu.new(node)

	self:registerScriptHandler(function(tag)
		    if "enter" == tag then
		        self:onEnter()
		    elseif "exit" == tag then
		    	self:onExit()
		    end
	    end)

	self:setPosition(node:getPosition())
	self.level = level

	return self
end

function memberFunc(self, func)
	return function(...)
		return func(self, ...)
	end
end

function AnimMenu:containsTouchLocation(pt)
	local position = self:convertToNodeSpace(pt)
    local  s = self:getContentSize()
    local touchRect = cc.rect(0, 0, s.width, s.height)

    return cc.rectContainsPoint(touchRect, position)
end

function AnimMenu:changeState(state)
	if (self.state == state) then
		return 
	end

	self.state = state
	if (state == "pressed") then
		self:runAction(cc.ScaleTo:create(0.1,1.2))
	else
		self:runAction(cc.ScaleTo:create(0.1,1))
	end
end

function AnimMenu:onTouchBegan(touch, event)
	if not self:containsTouchLocation(touch:getLocation()) then
		return false
	end

	self:changeState("pressed")

	self.startPoint = touch:getLocation()

	return true
end

function AnimMenu:onTouchMove(touch, event)
	if (self.state == "pressed") then
		if not self:containsTouchLocation(touch:getLocation()) then
			self:changeState("leave")
		end
	elseif (self.state == "leave") then
		if self:containsTouchLocation(touch:getLocation()) then
			self:changeState("pressed")
		end
	else
		return
	end

	if (cc.pGetDistance(self.startPoint, touch:getLocation()) > 50) then
		self:changeState(nil)
		self.startPoint = nil
	end
end

function AnimMenu:onTouchEnd(touch, event)
	if (self.state) then
		self:changeState(nil)
	end
end

function AnimMenu:onTouchCancel(touch, event)
	if (self.state) then
		self:changeState(nil)
	end
end

function AnimMenu:onEnter()
	local  listenner = cc.EventListenerTouchOneByOne:create()
	listenner:setSwallowTouches(true)

	listenner:registerScriptHandler(memberFunc(self, self.onTouchBegan), cc.Handler.EVENT_TOUCH_BEGAN )
	listenner:registerScriptHandler(memberFunc(self, self.onTouchMove), cc.Handler.EVENT_TOUCH_MOVED )
	listenner:registerScriptHandler(memberFunc(self, self.onTouchEnd), cc.Handler.EVENT_TOUCH_ENDED )
	listenner:registerScriptHandler(memberFunc(self, self.onTouchCancel), cc.Handler.EVENT_TOUCH_CANCELLED )

	local eventDispatcher = self:getEventDispatcher()
	eventDispatcher:addEventListenerWithFixedPriority(listenner, 1 + self.level)
	self.listenner = listenner
end

function AnimMenu:onExit()
	self:getEventDispatcher():removeEventListener(self.listenner)
end